package com.le.tester.javaThink.fourth.concurrency.waxomatic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/11/24 11:54
 * description：先抛光，后打蜡(wax)
 */

class Car {
    //默认不开启打蜡
    private boolean waxOn = false;

    //打蜡
    public synchronized void waxed() {
        waxOn = true;
        notifyAll();
    }

    //抛光
    public synchronized void buffed() {
        //此时不打蜡
        waxOn = false;
        notifyAll();
    }

    //等待打蜡，等到waxOn==true
    public synchronized void waitForWaxing() throws InterruptedException {
        while (!waxOn)
            wait();
    }

    //等待抛光，等到waxOn==false
    public synchronized void waitForBuffing() throws InterruptedException {
        while (waxOn)
            wait();
    }

}

//打蜡开
class WaxOn implements Runnable {
    private Car car;

    public WaxOn(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
//没有执行中断
        try {
            while (!Thread.interrupted()) {
                System.out.println("Wax On");
                TimeUnit.MILLISECONDS.sleep(200);
                car.waxed();
                car.waitForBuffing();
            }
        } catch (Exception e) {
            System.out.println("Exiting via interrupting");
        }
        System.out.println("Ending wax on task");
    }
}

//打蜡关
class WaxOff implements Runnable {

    private Car car;

    public WaxOff(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                car.waitForWaxing();
                System.out.println("Wax Off");
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();
            }
        } catch (Exception e) {
            System.out.println("Exiting via interrupt");
        }
        System.out.println("Ending Wax Off task");
    }
}

public class WaxOMatic {
    public static void main(String[] args) throws InterruptedException {
        Car car = new Car();
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(new WaxOn(car));
        service.submit(new WaxOff(car));
        TimeUnit.SECONDS.sleep(5);
        service.shutdownNow();
    }
}
